# coding:utf-8

import os
from io import BytesIO
import base64
import time
import uuid
import json

from PIL import Image
from flask import request, jsonify, current_app
from flask_restful import Api, Resource

from app.extensions import im_sync_proxy
from app.api.ip_utils import ip_util
from common.im_util import im_client
from app.op.constant import UserType, HAD_POPUP_PROMPT_SET
from app.op.models import Area, User, UserInfo
from .user_schemas import (
    user_schema, user_edit_schema, user_mobile_schema, user_avatar_schema,
    user_notify_schema)
from app.token import AuthToken
from .supplier_codes import NOT_ENGINEER
from .views import Response, AuthResource
from .codes import SUCCESS, PARAMS_ILLEGAL

api = Api()


@api.resource('/User/getUserInfo')
class UserInfoResource(Resource):
    """
    created by chenhj at 2017/8/10
    获取用户基本信息
    """
    def post(self):
        """
        created by chenhj at 2017/8/10

        """
        token = request.cookies.get('opc_token')
        user = AuthToken.verify_auth_token(token)
        if user:
            user_info = {
                'user': user_schema.dump(user)[0]
            }
            user_info['user']['opening_time'] = None
            enterprise = user.enterprises.first()
            if enterprise:
                if enterprise.valid:
                    user_info['user']['level'] = enterprise.level
                    user_info['user']['level_display'] = enterprise.level_display
                user_info['user']['opening_time'] = enterprise.created_at
            resp = Response(SUCCESS, user_info)
        else:
            cookies_key = 'im_info'
            im_info = json.loads(request.cookies.get(cookies_key, '[]'))
            if not im_info:
                accid = uuid.uuid4().hex
                try:
                    im_token = im_client.apply_im_token(accid)
                except:
                    return Response(SUCCESS, {
                        'user': {
                            'type': 0,
                            'im_token': '',
                            'id': 0
                        }
                    })
                im_info = {
                    'accid': accid,
                    'im_token': im_token
                }
            user_info = {
                'user': {
                    'type': 0,
                    'im_token': im_info['im_token'],
                    'id': im_info['accid']
                }
            }
            # 把城市同步到im信息中
            ip_info = ip_util.find(request.remote_addr)
            try:
                im_sync_proxy.send(json.dumps(dict(
                    func='update_user_info',
                    kwargs={
                        'accid': im_info['accid'],
                        'city': ip_info[1]
                    }
                )))
            except:
                pass
            resp = jsonify(Response(SUCCESS, user_info))
            resp.set_cookie(cookies_key, json.dumps(im_info))
        return resp


@api.resource('/User/updateUser')
class UpdateUserResource(AuthResource):
    """
    created by chenhj at 2017/8/14
    更新用户信息
    """
    def post(self):
        """
        created by chenhj at 2017/8/14

        """
        data, errors = user_edit_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        # 更新用户信息
        self.user.nickname = data['nickname']
        self.user.gender = data['gender']
        self.user.prov = data['prov']
        self.user.city = data['city']
        if 'com' in data and data['com']:
            self.user.com = data['com']
        else:
            self.user.com = ''
        if 'pos' in data and data['pos']:
            self.user.pos = data['pos']
        else:
            self.user.pos = ''
        if 'addr' in data and data['addr']:
            self.user.addr = data['addr']
        else:
            self.user.addr = ''
        area_id = Area.get_area_id(data['prov'], data['city'])
        if area_id:
            self.user.area_id = area_id
        return Response(SUCCESS)


@api.resource('/User/getInfoByMobile')
class UserByMobileResource(Resource):
    """
    created by chenhj at 2017/8/14

    """
    def post(self):
        data, errors = user_mobile_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        user = User.get_by_args(mobile=data['mobile'])
        if user:
            user_info = {
                'user': user_schema.dump(user)[0]
            }
        else:
            user_info = {
                'user': {
                    'type': 0,
                    'im_token': '',
                    'id': ''
                }
            }
        return Response(SUCCESS, user_info)


@api.resource('/Img/uploadAvatar')
class UserAvatarResource(AuthResource):
    """
    created by chenhj at 2017/8/21
    上传用户头像
    """
    def post(self):
        """
        created by chenhj at 2017/8/21

        """
        # 不是工程商则直接返回
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        data, errors = user_avatar_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        im = Image.open(BytesIO(base64.b64decode(data['img'])))
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'img/avatar')
        filename = '{filename}.{format}'.format(
            format=im.format.lower(), filename=self.user.id
        )
        im.save('{path}/{filename}'.format(path=path, filename=filename), im.format)

        self.user.avatar = 'avatar/{filename}?{timestamp}'.format(
            filename=filename, timestamp=int(time.time())
        )
        return Response(SUCCESS, {
            'img': self.user.avatar_url
        })


@api.resource('/User/notify')
class UserNotifyUpdateResource(AuthResource):
    """
    created by chenhj at 12/01/2018

    """
    def post(self):
        """
        created by chenhj at 12/01/2018

        """
        data, errors = user_notify_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        if 'level_3_notify' in data:
            UserInfo.default_user_info(self.user.id).level_3_notify = data['level_3_notify']

        if 'sms_alter_notify' in data:
            UserInfo.default_user_info(self.user.id).sms_alter_notify = data['sms_alter_notify']
        return Response()


@api.resource('/gift/prompt')
class GiftPromptResource(AuthResource):
    """
    create by ld_wu 2018-05-23
    赠送弹窗记录
    """
    def post(self):
        current_app.redis.sadd(HAD_POPUP_PROMPT_SET, self.user.id)
        return Response()

